#include "curlRequest.h"
void sendGetRequest(char* url,size_t (*fn)(void*, size_t, size_t , void*))
{
    //初始化curl
    CURL *curl = curl_easy_init();
    //给curl设置对应选项(目标地址、回调函数、请求参数、发送文件)
    curl_easy_setopt(curl,CURLOPT_URL,url);
    //发送请求参数
    //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"xx=ssas&sadas=sds");
    //设置回调函数
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,fn);
    //发送请求
    CURLcode code = curl_easy_perform(curl);
    if (code != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(code));
    }
    //清理
    curl_easy_cleanup(curl);
}
void sendPostRequest(char* url,char*parmStr,size_t (*fn)(void*, size_t, size_t , void*))
{
    //初始化curl
    CURL *curl = curl_easy_init();
    //给curl设置对应选项(目标地址、回调函数、请求参数、发送文件)
    curl_easy_setopt(curl,CURLOPT_URL,url);
    //发送请求参数
    curl_easy_setopt(curl,CURLOPT_POSTFIELDS,parmStr);
    //设置回调函数
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,fn);
    //发送请求
    CURLcode code = curl_easy_perform(curl);
    if (code != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(code));
    }
    //清理
    curl_easy_cleanup(curl);
}
int downloadRes(char *url, char *saveFilePath)
{
    FILE *saveFile = fopen(saveFilePath,"wb");
    if (!saveFile) {
        perror("Failed to open file for writing");
        return -1;
    }
    CURL *curl = curl_easy_init();
    if (!curl) {
        fclose(saveFile);
        return -1;
    }
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // 可选：跟随重定向
    curl_easy_setopt(curl, CURLOPT_FILE, saveFile);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        fclose(saveFile);
        curl_easy_cleanup(curl);
        return -1;
    }
    fclose(saveFile);
    curl_easy_cleanup(curl);
    return 0;
}